﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlServerCe;
using NDde.Server;

namespace lCash
{
    public partial class MainForm : Form
    {
        private MyDDEServer server ;
        private SqlCeConnection cn = new SqlCeConnection(@"Data Source = db.sdf");
        private int split1Memory;
        private string drawString;
        private string colNames = "Номер,Код биржи,Дата торгов,Дата сделки,Дата расчетов,Время,Время(мкс),Период,Заявка,Бумага сокр.,Бумага,Код бумаги,Класс,Код класса,Тип сделки,Операция,Счет,Цена,Кол-во,Объем,Валюта,Валюта расчетов,Код расчетов,Доходность,Купонный %,Трейдер,Идентификатор рабочей станции,Дилер,Орг-я трейдера,Код клиента,Комментарий,Партнер,Орг-я партнера,Цена выкупа,Ставка РЕПО(%),Комиссия ТС,Клиринговая комиссия,ФБ комиссия,ТЦ комиссия,Доход(%) на дату выкупа,Сумма РЕПО,Объем выкупа РЕПО,Срок РЕПО,Начальный дисконт(%),Нижний дисконт(%),Верхний дисконт(%),Блокировка обеспечения,Вид сделки,Идентификатор счета,Исходный номер,Айсберг-заявка";

        public MainForm()
        {
            InitializeComponent();
        }
          

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            cn.Close();
            Application.Exit();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {   
            cn = new SqlCeConnection(@"Data Source = db.sdf");
            try
            {
                cn.Open();
            }
            catch (SqlCeException ex)
            {
                MessageBox.Show(ex.Message);
                Application.ExitThread();
            }
            this.ordersTableAdapter.Fill(this.dbDataSet.orders);
            drawString = "";
            server = new MyDDEServer("ddeServerMy");
            server.MyEbent += new myDelegate(test);
            server.Register();
          
        }       
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
           
        }
        public void test(string typeName)
        {
            string colLocal="";
            string[,] result = server.result;
            double[,] resultNum = server.resultNumbers;            
            string[] types = new string[result.GetLength(1)];
            int cnt = 0,idxField=0,affectedRows=0;
            for (int i = 1; i < result.GetLength(1); i++)
            {
                if (result[0, i] == "Номер") idxField = i;
                colLocal = colLocal + result[0, i] + ",";                
            }
            colLocal = colLocal.Substring(0, colLocal.Length-1);
            SqlCeCommand qChk = new SqlCeCommand("SELECT empty1 FROM orders WHERE orders.empty1=@f", cn);
            if (colNames.CompareTo(colLocal) == 0)
            {
                SqlCeCommand q = new SqlCeCommand("SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE [TABLE_NAME]='orders'", cn);
                try
                {
                    SqlCeDataReader dr = q.ExecuteReader();
                    while (dr.Read())
                    {
                        types[cnt] = dr.GetString(0);
                        cnt++;
                    }
                    q.CommandText = "INSERT INTO orders VALUES(";       
                    //SqlCeDataReader dr = q.ExecuteReader();
                    //dr.Read();
                    for (int i = 1; i < result.GetLength(0); i++)
                    {
                        for (int y = 1; y < result.GetLength(1); y++)
                        {
                            switch (types[y-1])
                            {
                                case "int":
                                    q.CommandText = q.CommandText + "@f" + y.ToString() + ",";                                    
                                    q.Parameters.AddWithValue("@f" + y.ToString(), resultNum[i, y]);
                                    break;
                                case "float":
                                    q.CommandText = q.CommandText + "@f" + y.ToString() + ",";                                                                        
                                    q.Parameters.AddWithValue("@f" + y.ToString(), resultNum[i, y]);   
                                    if (y==idxField)
                                        qChk.Parameters.AddWithValue("@f", resultNum[i, y]);
                                    break;
                                case "nvarchar":
                                    q.CommandText = q.CommandText + "@f" + y.ToString() + ",";
                                    if (result[i, y] == null) q.Parameters.AddWithValue("@f" + y.ToString(), "");
                                    else q.Parameters.AddWithValue("@f" + y.ToString(), result[i,y]);
                                    break;
                                case "datetime":
                                    q.CommandText = q.CommandText + "@f" + y.ToString() + ",";
                                    if ((result[i, y] == null) || (result[i, y] == "")) q.Parameters.AddWithValue("@f" + y.ToString(), "01.01.1900");
                                    else q.Parameters.AddWithValue("@f" + y.ToString(), result[i,y]);
                                    break;                                    
                            }                            
                        }
                        q.CommandText = q.CommandText.Substring(0, q.CommandText.Length - 1) + ")";
                        dr = qChk.ExecuteReader();
                        if (dr.Read()==false)
                            affectedRows = q.ExecuteNonQuery();
                        qChk.Parameters.Clear();
                        q.CommandText = "INSERT INTO orders VALUES(";
                        q.Parameters.Clear();                                                
                        //MessageBox.Show(affectedRows.ToString());                        
                    }
                    
                    /*
                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        MessageBox.Show(dr.GetName(i));
                    }
                     */
                }
                catch (SqlCeException ex)
                {
                    MessageBox.Show(ex.Message);
                }     
            }
            //msgDataGridView.Invoke(new Action(() => { msgDataGridView.Rows.Add(); }));
            ordersDataGridView.Invoke(new Action(() => { ordersTableAdapter.Fill(this.dbDataSet.orders); }));
            //ordersDataGridView.Invoke
            /*
            while (dr.Read())
            {//loop through the records one by one
                //0 gets the first columns data for this record
                //as an INT
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    MessageBox.Show(dr.GetFieldType(i).ToString());
                }                           
                //rd.GetInt32(0);
                //gets the second column as a string
                //rd.GetString(1);
            }
             */ 
           // string fName = "@f",fTemp;
            //SqlCeCommand q = new SqlCeCommand("INSERT INTO orders(empty1,[ codExch],dTorg,dDeal,dCalc,time,timeMks,period,bid,papershort,paper,codpaper,class,codclass,typecalc,op,acct,cost,count,vol,val,valorder,codorder,yield,coupon,trader,idWork,diler,orgTrader,codcust,details,partner,orgPartner,costRed,repo,commts,commcl,commfb,commtc,incomered,summrepo,volrepo,termrepo,discountb,lowdiscount,highdiscount,blockprov,viddeal,idacct,ishnum,icebid) VALUES(@f1,@f2,@f3,@f4,@f5,@f6,@f7,@f8,@f9,@f10,@f11,@f12,@f13,@f14,@f15,@f16,@f17,@f18,@f19,@f20,@f21,@f22,@f23,@f24,@f25,@f26,@f27,@f28,@f29,@f30,@f31,@f32,@f33,@f34,@f35,@f36,@f37,@f38,@f39,@f40,@f41,@f42,@f43,@f44,@f45,@f46,@f47,@f48,@f49,@f50,@f51)",cn);
            //SqlCeCommand q = new SqlCeCommand("INSERT INTO orders(empty1, [ codExch], dTorg) VALUES(@f1,@f2,@f3)", cn);            
            //string[,] result = server.result;
            /*
            for (int i = 0; i < result.GetLength(1); i++)
            {
                fTemp = fName + (i + 1).ToString();
                q.Parameters.AddWithValue(fTemp, result[1,i]);
            }   
             * */
           // q.Parameters.AddWithValue("@f1", "");
            //q.Parameters.AddWithValue("@f2", "");
            //q.Parameters.AddWithValue("@f3", null);
            /*
            try
            {
                int affectedRows = q.ExecuteNonQuery();
                MessageBox.Show(affectedRows.ToString());
            }
            catch (SqlCeException ex)
            {
                MessageBox.Show(ex.Message);
            }
             */
 
            /*for (int i = 0; i < result.GetLength(1); i++)
            {
                q.Parameters.AddWithValue("@f1", result[2, i]);
                q.Parameters.AddWithValue("@f2", result[2, i]);
            }
             * */
                        
        }

        private void panelLabel_MouseEnter(object sender, EventArgs e)
        {
           
        }

        

        private void button1_Click(object sender, EventArgs e)
        {            
            panelComponent.Visible = false;
            labelAcct.Visible = false;
            labelTicket.Visible = false;
            treeViewAcct.Visible = false;
            treeViewTickers.Visible = false;
            split1Memory = splitContainer1.SplitterDistance;
            splitContainer1.SplitterDistance = 40;
            buttonSetting.Text = "";
            buttonGlass.Text = "";
            buttonInquiry.Text = "";
            buttonOrders.Text = "";
            buttonLevelPrice.Text = "";
            drawString = "Сделки";
            panelFilter.BackColor = Color.White;
            
            
        }

        private void panelFilter_MouseEnter(object sender, EventArgs e)
        {
            if (panelComponent.Visible == false)
            {
                panelFilter.BackColor = Color.FromArgb(255,167,86);
            }
        }

        private void panelFilter_MouseLeave(object sender, EventArgs e)
        {
            if (panelComponent.Visible == false)
            {
                panelFilter.BackColor = Color.White;                
            }
        }

        private void panelFilter_MouseClick(object sender, MouseEventArgs e)
        {
            if (panelComponent.Visible == false)
            {
                panelComponent.Visible = true;
                labelAcct.Visible = true;
                labelTicket.Visible = true;
                treeViewAcct.Visible = true;
                treeViewTickers.Visible = true;
                splitContainer1.SplitterDistance = split1Memory;
                panelFilter.BackColor = System.Windows.Forms.Control.DefaultBackColor;
                buttonSetting.Text = "Настройка";
                buttonGlass.Text = "Стакан";
                buttonInquiry.Text = "Запросы";
                buttonOrders.Text = "Сделки";
                buttonLevelPrice.Text = "Уровни цен";
                drawString = "";
            }
        }

        private void buttonInquiry_Click(object sender, EventArgs e)
        {
            
        }

        private void label2_Paint(object sender, PaintEventArgs e)
        {
            
        }

        private void panelFilter_Paint(object sender, PaintEventArgs e)
        {
            System.Drawing.Graphics g = e.Graphics;
            System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 10);
            System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
            float x = 50.0F;
            float y = 150.0F;
            System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat();
            g.TranslateTransform(x, y);
            g.RotateTransform(270);
            g.DrawString(drawString, drawFont, drawBrush, -60, -40, drawFormat);
            drawFont.Dispose();
            drawBrush.Dispose();            
        }

        private void buttonSetting_Click(object sender, EventArgs e)
        {
            this.ordersTableAdapter.Fill(this.dbDataSet.orders);
        }

        private void ordersBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {

        }

        private void ordersBindingNavigatorSaveItem_Click_1(object sender, EventArgs e)
        {
            this.Validate();
            this.ordersBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.dbDataSet);

        }

        private void ordersDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {            
        }        
    }    
}
